const FormData = require("form-data");
const http = require("http");
const download = require("download");
const path = require("path");

const fileType = require("file-type");

const { hashConcatUrl } = require("../util/util");
const { getQiniuOldToken } = require("../service/get-qiniu-old-token");

const option = {
	"content-type":
		"multipart/form-data; boundary=----WebKitFormBoundarySORVwHXR1DbdfqFJ",
	Origin: "http://xcx.duomai.com",
	cookie:
		"AppKey=wxe2c44d06eac05e60;Token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ3eGUyYzQ0ZDA2ZWFjMDVlNjAiLCJhdWQiOiJ3eGUyYzQ0ZDA2ZWFjMDVlNjAiLCJqdGkiOiJ3eGUyYzQ0ZDA2ZWFjMDVlNjAiLCJpYXQiOjE1NDg3NDQzMDUsIm5iZiI6MTU0ODc0NDMwNSwiZXhwIjoxNTQ4NzUxNTA1LCJBcHBLZXkiOiJ3eGUyYzQ0ZDA2ZWFjMDVlNjAiLCJVc2VySUQiOiIyNDAyMzkiLCJPcGVuSWQiOiJva0VFWDBaSkVPZS1zaU5WZnFnWkRiOEloRG9jIiwiQ3JlYXRlVGltZSI6IjIwMTgtMDgtMDYgMTM6NDA6MDQifQ.g5u9aIrTr6W22e2R_ThfsLeB1-uQpqadXp1EB8hTDfE"
};
const replaceByUrl = url => {
	return new Promise((resolve, reject) => {
		if (!url) {
			return reject();
		}
		Promise.all([download(url), getQiniuOldToken()])
			.then(res => {
				const data = res[0];
				const qiniuToken = res[1].d;
				const fileExtra = path.extname(url) || fileType(data).ext;
				var form = new FormData();
				form.append("file", data, {
					filename: `file.${fileExtra}`
				});
				form.append("token", qiniuToken);
				var headers = form.getHeaders();
				headers.Cookie = option.cookie;
				var request = http.request(
					{
						method: "post",
						host: "up.qiniup.com",
						path: "/",
						headers: headers
					},
					function(res) {
						var str = "";
						res.on("data", function(buffer) {
							str += buffer;
						});
						res.on("end", () => {
                            var result = JSON.parse(str);
							resolve(
								hashConcatUrl(result.hash, "xcx-album-img")
							);
						});
					}
				);
				form.pipe(request);
			})
			.catch(err => {
				reject(err);
			});
	});
};
module.exports = {
	replaceByUrl
};
